<template>
  <div>
    <r-search
      :searchForm="searchForm"
      :searchHandle="searchHandle"
      :searchData="searchData"
    />
    <div class="contentBattery ">
      BatteryStatistics：
      <div class="div160" style="margin-left:40px">
        Total：<span class="span160">{{ batteryToptal || 0 }}</span
        >Group
      </div>
      <div class="div160">
        Cabinet：<span class="span160">{{ batteryToptal0 || 0 }}</span
        >Group
      </div>
      <div class="div160">
        Employ：<span class="span160">{{ batteryToptal1 || 0 }}</span
        >Group
      </div>
      <div style="width: 220px;">
        Leave Unused：<span class="span160">{{ batteryToptal2 || 0 }}</span
        >Group
      </div>
    </div>
    <r-table
      :tableHandles="tableHandles"
      :isSelection="false"
      :isIndex="false"
      :isPagination="true"
      :tableData="tableData"
      :tableCols="tableCols"
      :tablePage="tablePage"
      :isHandle="true"
      @refresh="init()"
    >
    </r-table>
    <r-form
      :formRules="formRules"
      :formHandle="formHandle"
      :formData="formData"
      :formCols="formCols"
      ref="elForm"
      labelWidth="140px"
      dialogWidth="600px"
      :isHandle="true"
    />
    <battery_details ref="battery_details"></battery_details>
    <div>
      <el-dialog
        width="35%"
        title="Control Battery"
        :visible.sync="dialogFormVisible"
      >
        <el-form style="display: flex;justify-content: center;">
          <el-form-item label="OperationsType" :label-width="formLabelWidth">
            <el-select
              placeholder="Please Select Operations Type"
              :clearable="true"
              v-model="agentValue"
              style="width:270px"
            >
              <el-option
                v-for="item in agentArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <el-form style="display: flex;justify-content: center;">
          <el-form-item label="Operations Value" :label-width="formLabelWidth">
            <el-select
              placeholder="Please Select Operations Value"
              :clearable="true"
              v-model="agentIdValue"
              style="width:270px"
            >
              <el-option
                v-for="item in agentIdArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="affirmAgentFn">Confirm</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 导入Template模态框 -->
    <uploadFileBattery
      v-if="uploadFile_fag"
      v-on:uploadFile_call="uploadFile_call"
    >
    </uploadFileBattery>
  </div>
</template>
<script>
import battery_details from "./cus/battery_details";
import uploadFileBattery from "../cus/uploadFileBattery";
import axios from "axios";
export default {
  components: {
    battery_details,
    uploadFileBattery
  },
  data() {
    return {
      uploadFile_fag: false, //控制导出Template模态框的显示隐藏
      searchData: {
        batteryName: "",
        typeId: "",
        deviceNo: "",
        batteryNo: "",
        id: "",
        status: "",
        onLine: ""
      },
      batteryToptal: 0,
      batteryToptal0: 0,
      batteryToptal1: 0,
      batteryToptal2: 0,
      searchForm: [
        {
          type: "input",
          prop: "batteryNo",
          placeholder: "Battery Number",
          width: 250
        },
        {
          type: "input",
          prop: "batteryName",
          placeholder: "Battery Name",
          width: 250
        },
        {
          type: "select",
          prop: "typeId",
          placeholder: "Battery Type",
          width: 250,
          options: []
        },
        {
          type: "input",
          prop: "deviceNo",
          placeholder: "Change Cabinet Number",
          width: 300
        },
        {
          type: "select",
          prop: "status",
          placeholder: "Battery Status",
          width: 240,
          options: [
            {
              label: "Charging",
              value: 0
            },
            {
              label: "Rent",
              value: 1
            },
            {
              label: "Leave Unused",
              value: 2
            }
          ]
        },
        {
          type: "select",
          prop: "onLine",
          placeholder: "Online Or Offline",
          width: 270,
          options: [
            {
              label: "Offline",
              value: 0
            },
            {
              label: "Online",
              value: 1
            }
          ]
        }

        // {
        //   type: 'select',
        //   prop: 'commonType',
        //   placeholder: 'Please Select',
        //   width: 150,
        //   options:[
        //     {label:'Public',value:'1'},
        //     {label:'Private',value:'2'},
        //   ],
        //   isShow:()=>{
        //     return sessionStorage.role=='platform'?false:true;
        //   }
        // }
      ],
      searchHandle: [
        {
          label: "Search",
          type: "success",
          plain: true,
          icon: "el-icon-search",
          handle: e => {
            this.zeroFn();
            this.init();
          }
        },
        {
          label: "Reset",
          buttonss: true,
          icon: "el-icon-refresh-right",
          handle: e => {
            this.searchData = {
              batteryName: "",
              typeId: "",
              deviceNo: "",
              batteryNo: "",
              id: "",
              status: "",
              onLine: ""
            };
            this.zeroFn();
            this.init();
          }
        }
      ],

      tableHandles: [
        // {
        //   label: "Public",
        //   type: "primary",
        //   handle: e => this.elFormVisible()
        // },
        // {
        //   label: "自建",
        //   type: "primary",
        //   handle: e => this.elFormVisible()
        // },
        {
          label: "Add",
          type: "primary",
          plain: true,
          icon: "el-icon-plus",
          handle: e => this.elFormVisible()
        },
        {
          label: "Download Battery Template",
          type: "primary",
          plain: true,
          icon: "el-icon-download",
          handle: async e => {
            const res = await this.apis.batteryImportTemplate({});
            // console.log("res---", res.msg);
            this.$message({
              type: res.code == 200 ? "success" : "error",
              message: res.code == 200 ? "success" : "error"
            });
            location.href = process.env.VUE_APP_URL + res.msg;
          }
        },
        {
          label: "Battery Data Import",
          type: "primary",
          icon: "el-icon-upload2",
          plain: true,
          handle: e => {
            this.uploadFile_fag = true;
          }
        },
        {
          label: "Export Battery Data",
          type: "primary",
          icon: "el-icon-download",
          plain: true,
          handle: async e => {
            const res = await this.apis.batteryExport(this.searchData);
            console.log(333, this.searchData, res.msg);
            this.$message({
              type: res.code == 200 ? "success" : "error",
              message: res.code == 200 ? "success" : "error"
            });
            location.href = process.env.VUE_APP_URL + res.msg;
          }
        }
      ],
      batteryTypeArr: [],
      tableData: [],
      tableCols: [
        // {
        //   label: "UserID",
        //   prop: "id",
        // },
        {
          label: "Name",
          prop: "batteryName"
        },
        {
          label: "QR Code",
          type: "image",
          width: 100,
          prop: "qrCode"
        },
        {
          label: "Battery Number",
          prop: "batteryNo",
          width: 220
        },
        {
          label: "Battery Status",
          prop: "status",
          formatter: e =>
            e.status == 0
              ? "Charging"
              : e.status == 1
              ? "Rent"
              : e.status == 2
              ? "Leave Unused"
              : ""
        },
        {
          label: "Online/Offline",
          prop: "onLine",
          formatter: e =>
            e.onLine == 0 ? "Offline" : e.onLine == 1 ? "Online" : "",
          itemClass: e =>
            e.onLine == 0 ? "danger" : e.onLine == 1 ? "success" : ""
        },
        {
          label: "Type Name",
          prop: "typeId",
          formatter: e => {
            let name = "";
            var filteredArray = this.batteryTypeArr.filter(function(obj) {
              if (obj.id === e.typeId) {
                return (name = obj.typeName);
              }
            });
            return name;
          }
        },
        // {
        //   label: "BatteryType",
        //   prop: "typeId",
        // },
        {
          label: "Category",
          prop: "commonType",
          formatter: row => {
            if (row.commonType == 1) {
              return "Public";
            } else if (row.commonType == 2) {
              return "Private";
            }
          }
        },
        // {
        //   label: '所属信息',
        //   prop: 'money'
        // },
        // {
        //   label: "BatteryStatus",
        //   prop: "btState",
        //   formatter: (row) => {
        //     if (row.btState == 0) {
        //       return "移动";
        //     } else if (row.btState == 1) {
        //       return "静止";
        //     } else if (row.btState == 2) {
        //       return "存储";
        //     } else if (row.btState == 3) {
        //       return "休眠";
        //     }
        //   },
        // },
        {
          label: "Device Number",
          prop: "deviceNo"
        },
        // {
        //   label: '持有User信息',
        //   prop: 'giftMoney'
        // },
        // {
        //   label: "Update Time",
        //   prop: "lastTime",
        // },
        {
          label: "Operations",
          type: "button",
          width: 280,
          btnList: [
            {
              label: "Edit",
              type: "primary",
              size: "mini",
              plain: true,
              style: { "margin-bottom": "5px" },
              handle: row => this.elFormDetail(row)
            },
            // {
            //   label: 'Delete',
            //   type: 'text',
            //   handle: (row) => this.TableDel('/pack', { id: row.id }, 'del')
            // },
            {
              label: "Details",
              type: "success",
              size: "mini",
              plain: true,
              handle: async row => {
                const res = await this.apis.battery_detail(row);
                this.$refs.battery_details.battery_info = res.data;
                this.$refs.battery_details.show = true;
                setTimeout(() => {
                  this.$refs.battery_details.map();
                }, 10);
              }
            },
            {
              label: "Control Battery",
              type: "primary",
              size: "mini",
              plain: true,
              handle: row => {
                this.dialogFormVisible = true;
                this.batteryId = row.batteryNo;
              }
            }
          ]
        }
      ],

      tablePage: { limit: 10, page: 1, total: 0 },
      agentArr: [
        { label: "Battery Restart", value: 0 },
        { label: "Battery Charging And Discharging Control", value: 1 }
      ],
      agentIdArr: [],
      dialogFormVisible: false,
      formLabelWidth: "130px",
      agentValue: null,
      agentIdValue: null,
      batteryId: "",
      formData: {
        batteryName: "",
        batteryNo: "",
        typeId: "",
        typeVt: "",
        operatorId: "",
        agentId: ""
      },
      formCols: [
        {
          type: "input",
          label: "Battery Name",
          width: 350,
          prop: "batteryName"
        },
        {
          type: "input",
          label: "Battery Number",
          width: 350,
          prop: "batteryNo"
        },
        {
          type: "select",
          label: "Battery Type",
          width: 350,
          prop: "typeId",
          options: []
        },
        {
          type: "input",
          label: "Voltage(V)",
          width: 350,
          prop: "typeVt",
          isDisabled: e => true
        },
        {
          type: "select",
          label: "Operator",
          width: 350,
          prop: "operatorId",
          options: [],
          isShow: row => {
            return sessionStorage.role == "platform" ? true : false;
          }
        },
        {
          type: "select",
          label: "Belonging Agent",
          width: 350,
          prop: "agentId",
          options: [],
          // isDisabled: e => true,
          isShow: row => {
            return sessionStorage.role == "operator" ? true : false;
          }
        }
      ],
      formRules: {
        batteryName: [
          { required: true, message: "Please Enter", trigger: "blur" }
        ],
        batteryNo: [
          { required: true, message: "Please Enter", trigger: "blur" }
        ],
        typeId: [{ required: true, message: "Please Select", trigger: "blur" }],
        // typeVt: [{ required: true, message: "Please Enter", trigger: "blur" }],
        operatorId: [
          { required: true, message: "Please Select", trigger: "blur" }
        ],
        agentId: [{ required: true, message: "Please Select", trigger: "blur" }]
      },
      formHandle: [
        {
          label: "Cancel",
          handle: e => this.elFormVisible()
        },
        {
          label: "Confirm",
          type: "success",
          handle: e => this.elFormSubmit()
        }
      ],
      dianyaList: []
    };
  },
  watch: {
    "formData.typeId": {
      handler(newValue) {
        if (newValue) {
          this.dianyaList.forEach(i => {
            if (i.id === newValue) {
              this.formData.typeVt = i.voltage;
            }
          });
        } else {
          return;
        }
      },
      deep: true // 深度监听
    },
    agentValue: {
      handler(newValue) {
        if (newValue === 0) {
          this.agentIdArr = [];
          this.agentIdValue = "";
          this.agentIdArr = [
            { label: "Restart DTU", value: 0 },
            { label: "Restart BMS", value: 1 },
            { label: "Whole Restart", value: 2 }
          ];
        } else if (newValue === 1) {
          this.agentIdArr = [];
          this.agentIdValue = "";
          this.agentIdArr = [
            { label: "Turn Off Charging And Discharging Current", value: 0 },
            { label: "Enable Charging And Discharging Current", value: 3 }
          ];
        }
      },
      deep: true // 深度监听
    },
    dialogFormVisible: {
      handler(newValue) {
        if (newValue) {
          this.agentValue = "";
          this.agentIdValue = "";
        }
      },
      deep: true // 深度监听
    }
  },
  computed: {},
  mounted() {
    this.init();
    this.batteryTypeList();
    this.operator_list();
    this.agent_list();
    this.batteryToptalFn();
  },
  methods: {
    zeroFn() {
      this.tablePage.limit = 10;
      this.tablePage.page = 1;
      this.tablePage.total = 0;
    },
    async affirmAgentFn() {
      if (this.agentValue !== 0 && this.agentValue !== 1) {
        this.$message({
          message: "Please Select Operations Type",
          type: "error"
        });
        return false;
      }
      if (
        (this.agentValue === 0 &&
          this.agentIdValue !== 0 &&
          this.agentIdValue !== 1 &&
          this.agentIdValue !== 2) ||
        (this.agentValue === 1 &&
          this.agentIdValue !== 0 &&
          this.agentIdValue !== 3)
      ) {
        this.$message({
          message: "Please Select Operations Value",
          type: "error"
        });
        return false;
      }
      this.dialogFormVisible = false;
      let params = {
        batteryNo: this.batteryId,
        type: this.agentValue,
        typeValue: String(this.agentIdValue)
      };
      console.log(2222, params);
      let res = await this.apis.batterySetBattery(params);

      this.$message({
        type: res.code == 200 ? "success" : "error",
        message: res.msg
      });
    },
    async batteryToptalFn() {
      let res = await this.apis.batteryBatteryCountget();
      console.log(res);
      let list = res.data || [];
      if (list.length !== 0) {
        list.forEach(i => {
          if (i.batteryStatus === 0) {
            this.batteryToptal0 = i.batteryCount;
          } else if (i.batteryStatus === 1) {
            this.batteryToptal1 = i.batteryCount;
          } else if (i.batteryStatus === 2) {
            this.batteryToptal2 = i.batteryCount;
          }
          this.batteryToptal =
            this.batteryToptal0 + this.batteryToptal1 + this.batteryToptal2;
        });
      }
    },
    async init() {
      let parm = {
        ...this.searchData,
        ...{
          pageNum: this.tablePage.page,
          pageSize: this.tablePage.limit
        }
      };
      let res = await this.apis.battery_list(parm);
      if (res) {
        this.tableData = res.rows;
        this.tablePage.total = res.total;
      }
    },
    async elFormSubmit() {
      this.$refs.elForm.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (this.formData.id) {
            let res = await this.apis.battery_updata(this.formData);
            this.$message({
              type: res.code == 200 ? "success" : "error",
              message: res.msg
            });
            if (res) {
              this.init();
              this.elFormVisible();
            }
          } else {
            let res = await this.apis.battery_save(this.formData);
            this.$message({
              type: res.code == 200 ? "success" : "error",
              message: res.msg
            });
            if (res) {
              this.init();
              this.elFormVisible();
            }
          }
        }
      });
    },
    async changestate(id) {
      let res = await this.api.packchange({ id });
      if (res) {
        this.init();
      }
    },
    elFormDetail(row) {
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = row[key];
      });
      this.formData.id = row.id;
      this.elFormVisible();
    },
    async batteryTypeList() {
      // const res=await this.apis.batteryTypeList({
      //   pageNum:1,
      //   pageSize:10000,
      //   commonType:'1'
      // });
      //
      // let list=res.rows;

      const res2 = await this.apis.batteryTypeList({
        pageNum: 1,
        pageSize: 10000,
        commonType: "2"
      });

      const list2 = res2.rows;
      this.batteryTypeArr = res2.rows;
      // list=list.concat(list2);

      let options = [];
      let options1 = [];
      this.dianyaList = [];
      this.dianyaList = list2;
      list2.map(res => {
        options.push({
          label: res.typeName,
          value: res.id
        });
        options1.push({
          label: res.typeName,
          value: res.id
        });
      });
      this.formCols[this.labIndex2(this.formCols, "typeId")].options = options;
      this.searchForm[
        this.labIndex2(this.searchForm, "typeId")
      ].options = options1;
    },
    async operator_list() {
      const res = await this.apis.operator_list({
        pageNum: 1,
        pageSize: 10000
      });
      const list = res.rows;
      let options = [];
      list.map(res => {
        options.push({
          label: res.name,
          value: res.id
        });
      });
      this.formCols[
        this.labIndex2(this.formCols, "operatorId")
      ].options = options;
    },
    async agent_list() {
      const res = await this.apis.agent_list({
        pageNum: 1,
        pageSize: 1000000
      });
      const list = res.rows || [];
      let options = [];
      list.map(res => {
        options.push({
          label: res.name,
          value: res.id
        });

        this.formCols[
          this.labIndex2(this.formCols, "agentId")
        ].options = options;
      });
    },
    // 导入Data（子传父 接受从子组件传过来的方式与参数）
    uploadFile_call(fag) {
      this.uploadFile_fag = false;

      if (fag) {
        setTimeout(() => {
          this.init();
        }, 1500);
      }
    }
  }
};
</script>
<style scoped lang="scss">
.el-icon-search {
  margin-right: 0.42rem;
}

.Tip {
  margin-left: 0.83rem;
}

.contentBattery {
  font-size: 15px;
  font-weight: 700;
  margin-bottom: 15px;
  width: 950px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  position: relative;
  left: 0px;
  top: 0;
}

.div160 {
  width: 190px;
}

.span160 {
  margin-right: 5px;
  color: #000cff;
}
</style>
